package cn.fzkj.mapper;

import cn.fzkj.domain.SysJob;
import cn.fzkj.jooq.codegen.Tables;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Table;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

import static cn.fzkj.jooq.codegen.Tables.SYS_JOB;

@Repository
public class SysJobMapper {

    @Autowired
    private DSLContext dslContext;


    public List<SysJob> selectJobAll() {
        return dslContext.selectFrom(SYS_JOB).fetch(item -> item.into(SysJob.class));
    }


    public List<SysJob> selectJobList(SysJob job) {
        List<Condition> conditions = buildCondition(job);
        return dslContext.selectFrom(SYS_JOB).where(conditions).fetch(item -> item.into(SysJob.class));
    }

    private List<Condition> buildCondition(SysJob job){
        List<Condition> conditions = new ArrayList<>();
        if (StringUtils.isNotBlank(job.getJobName())){
            conditions.add(SYS_JOB.JOB_NAME.like("%" + job.getJobName() + "%"));
        }
        if (StringUtils.isNotBlank(job.getJobGroup())){
            conditions.add(SYS_JOB.JOB_GROUP.eq(job.getJobGroup()));
        }
        if (StringUtils.isNotBlank(job.getStatus())){
            conditions.add(SYS_JOB.STATUS.eq(job.getStatus()));
        }
        return conditions;
    }

    public SysJob selectJobById(Long jobId) {
        return dslContext.selectFrom(SYS_JOB).where(SYS_JOB.JOB_ID.eq(jobId)).fetchOne(item -> item.into(SysJob.class));
    }

    public int updateJob(SysJob job) {
        return 1;
    }

    public int deleteJobById(Long jobId) {
        return 1;
    }

    public int insertJob(SysJob job) {
        int execute = dslContext.insertInto(SYS_JOB)
                .columns(SYS_JOB.JOB_ID, SYS_JOB.JOB_NAME, SYS_JOB.JOB_GROUP, SYS_JOB.INVOKE_TARGET, SYS_JOB.CRON_EXPRESSION,
                        SYS_JOB.MISFIRE_POLICY, SYS_JOB.CONCURRENT, SYS_JOB.STATUS)
                .values(job.getJobId(), job.getJobName(), job.getJobGroup(), job.getInvokeTarget(), job.getCronExpression(), job.getMisfirePolicy(), job.getConcurrent(), job.getStatus())
                .execute();
        return execute;
    }
}
